package com.lt.bookkeeping.http;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * @author LiuTong
 */
public class RequestHttp {

    private final String HTTP = "http://";
    private final String HTTPS = "https://";
    private final String PORT = ":12345";
    private Call mCall;
    private final String mUrl;
    private final long WRITE_OUT_TIME = 10*1000
            ,READ_OUT_TIME = 10*1000
            ,CALL_OUT_TIME = 10*1000;

    public RequestHttp(String url) {
        if(!url.startsWith(HTTPS)){
            if(url.startsWith(HTTP)){
               url = url.replace(HTTP,HTTPS);
            }else {
                url = HTTPS + url;
            }
        }
        if(!url.endsWith(PORT)){
            url = url + PORT;
        }
        this.mUrl = url;
        createClient();
    }

    private void createClient() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_OUT_TIME, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_OUT_TIME, TimeUnit.MILLISECONDS)
                .callTimeout(CALL_OUT_TIME, TimeUnit.MILLISECONDS)
                .build();
        FormBody formBody = new FormBody.Builder()
                .add("userId","liutong")
                .add("password","12456")
                .build();

         Request request = new Request.Builder()
                 .get()
                 .url(mUrl)
//                 .post(formBody)
                 .build();

         mCall = okHttpClient.newCall(request);
    }

    public void startRequest(Callback callback){
        if(mCall != null){
            if(mCall.isExecuted()){
                mCall.clone().enqueue(callback);
            }else {
                mCall.enqueue(callback);
            }
        }

    }

}
